<!--
 * @Description: 端口监控
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-06-25 10:05:09
 * @LastEditTime: 2021-11-23 16:32:25
 * @LastEditors: 0001100986/LiuShuai
-->
<template>
  <div class="device device-port">
    <div class="title">
      <i
        class="iconfont icon-wangluo"
        style="color: rgb(24, 144, 255); background: rgb(230, 247, 255);"
      ></i> 端口监控
    </div>
    <div class="content">
      <el-row>
        <el-col :xs="24" :sm="12" :lg="12">
          <el-radio-group v-model="type">
            <el-radio-button label="当前"></el-radio-button>
            <el-radio-button label="24小时"></el-radio-button>
            <el-radio-button label="自定义"></el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="12" v-if="type==='自定义'">
          <el-date-picker
            v-model="dayTimes"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="otherInit"
            :picker-options="options"
          ></el-date-picker>
        </el-col>
      </el-row>
      <el-alert v-if="type==='24小时'" title="24小时监控范围：今天0点 - 当前时间点" type="info" center show-icon></el-alert>
      <div id="charts" style="min-height: 400px;" v-loading="loading"></div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { Chart } from '@antv/g2';

export default {
  name: 'port',
  props: ['neId', 'name', 'vlan'],
  data () {
    return {
      type: '当前',
      loading: false,
      portChart: null,
      portData: [],
      // 定时器
      timerPort: null,
      // 时间区间
      dayTimes: [dayjs(dayjs().subtract(7, 'day').format('YYYY-MM-DD') + ' 00:00:00').format(), dayjs(dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 23:59:59').format()],
      // 可选时间范围
      options: {
        disabledDate (time) {
          // 昨天时间戳
          let end = dayjs(dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 23:59:59').valueOf();
          // 一个月
          let one = 30 * 24 * 3600 * 1000;
          // 昨天30天前时间戳
          let start = end - one;
          return time.getTime() < start || time.getTime() > end;
        }
      }
    };
  },
  filters: {
    filterBPS (value) {
      if (value >= 0 && value < 1000) {
        value = value + 'bps';
      }
      if (value >= 1000 && value < 1000000) {
        value = (value / 1000).toFixed(2) + 'Kbps';
      }
      if (value >= 1000000) {
        value = (value / 1000000).toFixed(2) + 'Mbps';
      }
      return value;
    }
  },
  // 销毁
  beforeDestroy () {
    let _this = this;
    // 执行销毁定时器
    _this.clearPortChart();
  },
  watch: {
    type: {
      handler (val) {
        let _this = this;
        if (val === '当前') {
          _this.clearPortChart();
          _this.chartInit();
        }
        if (val === '24小时') {
          _this.clearPortChart();
          _this.hoursInit();
        }
        if (val === '自定义') {
          _this.clearPortChart();
          _this.otherInit();
        }
      }
    }
  },
  // DOM加载完成后执行
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      _this.timerPort = null;
      // 重置实时统计数据
      _this.portData = [];
      let charts = document.getElementById('charts');
      if (charts) {
        document.getElementById('charts').innerHTML = '';
      }
      _this.chartInit();
    });
  },
  methods: {
    // 清除定时器
    clearPortChart () {
      let _this = this;
      // 清除定时器
      clearInterval(_this.timerPort);
      _this.timerPort = null;
      // 重置实时统计数据
      _this.portData = [];
      let charts = document.getElementById('charts');
      if (charts) {
        // 销毁chart
        document.getElementById('charts').innerHTML = '';
      }
    },
    // 创建设备端口监控图表
    chartInit () {
      let _this = this;
      // 创建图表
      _this.portChart = new Chart({
        container: 'charts',
        autoFit: true,
        height: 400
      });
      _this.loading = true;
      // X轴显示格式
      _this.portChart.scale('year', {
        type: 'time',
        mask: 'YYYY-MM-DD HH:mm:ss'
      });
      _this.portChart.axis('year', {
        label: {
          formatter: (text, item, index) => {
            text = text.substr(11, text.length);
            return text;
          }
        }
      });
      // Y轴参数设置
      _this.portChart.scale('value', {
        nice: true
      });
      // 图表提示框设置
      _this.portChart.tooltip({
        showCrosshairs: true,
        shared: true,
        customItems: (items) => {
          items.map(ind => {
            if (ind.name === '端口发送流量速率' || ind.name === '端口接收流量速率') {
              ind.value = _this.$options.filters['filterBPS'](ind.value);
            } else {
              ind.value = ind.value + '%';
            }
          });
          return items;
        },
      });
      // 显示文字色值
      _this.portChart.line().position('year*value').color('country', ['#6495fa', '#5ad8a6', '#D47625', '#60A38B']);
      // 图表初始值
      _this.$http.post({
        url: '/api/resource/nemng/command/' + _this.neId,
        data: {
          commandCode: 'pm.router.current.get',
          paras: {
            poId: '003'
          }
        }
      }).then(res => {
        let { dataList } = res;
        for (let i = 0; i < dataList.length; i++) {
          let onName = _this.name.toUpperCase();
          let portName = [onName.substring(0, onName.indexOf('-')), onName.substring(onName.indexOf('-') + 1, onName.indexOf('/')), onName.substring(onName.indexOf('/') + 1, onName.length)];
          let arr = dataList[i].name.split(',');
          let list = arr[1].split('=');
          let ports = [list[0], arr[0].substring(arr[0].lastIndexOf('/') + 1, arr[0].length), list[1]];
          if (_this.vlan) {
            portName.push(_this.vlan);
            if (dataList[i].name.indexOf('子接口') > -1) {
              ports.push(arr[2].substring(arr[2].indexOf('=') + 1, arr[2].length));
            }
          }
          let parStr = portName.join(',');
          let sonStr = ports.join(',');
          if (parStr === sonStr) {
            // eslint-disable-next-line guard-for-in
            for (let key in dataList[i].values) {
              if (key === '003_003') {
                _this.portData.push({
                  country: '端口发送流量速率',
                  year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  value: dataList[i].values[key]
                });
              }
              if (key === '003_002') {
                _this.portData.push({
                  country: '端口接收流量速率',
                  year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  value: dataList[i].values[key]
                });
              }
              if (key === '003_004') {
                _this.portData.push({
                  country: '接收方向带宽利用率',
                  year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  value: dataList[i].values[key]
                });
              }
              if (key === '003_005') {
                _this.portData.push({
                  country: '发送方向带宽利用率',
                  year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  value: dataList[i].values[key]
                });
              }
            }
            _this.portChart.data(_this.portData);
          }
        }
      });
      _this.portChart.render();
      // 开始定时器请求
      _this.timerPort = setInterval(() => {
        _this.$http.post({
          url: '/api/resource/nemng/command/' + _this.neId,
          data: {
            commandCode: 'pm.router.current.get',
            paras: {
              poId: '003'
            }
          },
          loading: false
        }).then(res => {
          let { dataList } = res;
          for (let i = 0; i < dataList.length; i++) {
            let onName = _this.name.toUpperCase();
            let portName = [onName.substring(0, onName.indexOf('-')), onName.substring(onName.indexOf('-') + 1, onName.indexOf('/')), onName.substring(onName.indexOf('/') + 1, onName.length)];
            let arr = dataList[i].name.split(',');
            let list = arr[1].split('=');
            let ports = [list[0], arr[0].substring(arr[0].lastIndexOf('/') + 1, arr[0].length), list[1]];
            if (_this.vlan) {
              portName.push(_this.vlan);
              if (dataList[i].name.indexOf('子接口') > -1) {
                ports.push(arr[2].substring(arr[2].indexOf('=') + 1, arr[2].length));
              }
            }
            let parStr = portName.join(',');
            let sonStr = ports.join(',');
            if (parStr === sonStr) {
              // eslint-disable-next-line guard-for-in
              for (let key in dataList[i].values) {
                if (key === '003_003') {
                  _this.portData.push({
                    country: '端口发送流量速率',
                    year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    value: dataList[i].values[key]
                  });
                }
                if (key === '003_002') {
                  _this.portData.push({
                    country: '端口接收流量速率',
                    year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    value: dataList[i].values[key]
                  });
                }
                if (key === '003_004') {
                  _this.portData.push({
                    country: '接收方向带宽利用率',
                    year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    value: dataList[i].values[key]
                  });
                }
                if (key === '003_005') {
                  _this.portData.push({
                    country: '发送方向带宽利用率',
                    year: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    value: dataList[i].values[key]
                  });
                }
              }
              // 实时更新图表显示
              _this.portChart.changeData(_this.portData);
              _this.loading = false;
            }
          }
        }).catch(err => {
          // 执行销毁
          _this.clearPortChart();
          _this.loading = false;
        });
      }, 5000);
    },
    // 24小时监控日志
    hoursInit () {
      let _this = this;
      // 创建图表
      _this.portChart = new Chart({
        container: 'charts',
        autoFit: true,
        height: 400
      });
      _this.loading = true;
      // X轴显示格式
      _this.portChart.scale('year', {
        type: 'time',
        mask: 'YYYY-MM-DD HH:mm:ss'
      });
      _this.portChart.axis('year', {
        label: {
          formatter: (text, item, index) => {
            text = text.substr(11, text.length);
            return text;
          }
        }
      });
      // Y轴参数设置
      _this.portChart.scale('value', {
        nice: true,
        min: 0
      });
      // 图表提示框设置
      _this.portChart.tooltip({
        showCrosshairs: true,
        shared: true,
        customItems: (items) => {
          items.map(ind => {
            if (ind.name === '端口发送流量速率' || ind.name === '端口接收流量速率') {
              ind.value = _this.$options.filters['filterBPS'](ind.value);
            } else {
              ind.value = ind.value + '%';
            }
          });
          return items;
        },
      });
      // 显示文字色值
      _this.portChart.line().position('year*value').color('country', ['#D47625', '#60A38B', '#6495fa', '#5ad8a6']);
      // 获取当天时间的零点
      let timestamp = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
      let startTime = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
      let endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      _this.$http.post({
        url: '/api/sdwan/pm/appoint',
        data: {
          neId: Number(_this.neId),
          poId: '003',
          name: _this.name,
          startTime: startTime,
          endTime: endTime
        }
      }).then(res => {
        let { status, resultBody } = res;
        if (resultBody.length === 0) {
          _this.$message.warning('暂无数据！');
          _this.portChart.changeData([]);
          _this.loading = false;
        } else {
          resultBody.splice(0, 1);
          if (status === '0') {
            let arry = [];
            for (let i = 0; i < resultBody.length; i++) {
              let onName = _this.name.toUpperCase();
              let portName = [onName.substring(0, onName.indexOf('-')), onName.substring(onName.indexOf('-') + 1, onName.indexOf('/')), onName.substring(onName.indexOf('/') + 1, onName.length)];
              let arr = resultBody[i].data.name.split(',');
              let list = arr[1].split('=');
              let ports = [list[0], arr[0].substring(arr[0].lastIndexOf('/') + 1, arr[0].length), list[1]];
              if (_this.vlan) {
                portName.push(_this.vlan);
                if (resultBody[i].data.name.indexOf('子接口') > -1) {
                  ports.push(arr[2].substring(arr[2].indexOf('=') + 1, arr[2].length));
                }
              }
              let parStr = portName.join(',');
              let sonStr = ports.join(',');
              if (parStr === sonStr) {
                // eslint-disable-next-line guard-for-in
                for (let key in resultBody[i].data.values) {
                  // eslint-disable-next-line max-depth
                  if (key === '003_003') {
                    arry.push({
                      country: '端口发送流量速率',
                      year: resultBody[i].time.substr(0, 19),
                      value: resultBody[i].data.values[key]
                    });
                  }
                  // eslint-disable-next-line max-depth
                  if (key === '003_002') {
                    arry.push({
                      country: '端口接收流量速率',
                      year: resultBody[i].time.substr(0, 19),
                      value: resultBody[i].data.values[key]
                    });
                  }
                  // eslint-disable-next-line max-depth
                  if (key === '003_004') {
                    arry.push({
                      country: '接收方向带宽利用率',
                      year: resultBody[i].time.substr(0, 19),
                      value: resultBody[i].data.values[key]
                    });
                  }
                  // eslint-disable-next-line max-depth
                  if (key === '003_005') {
                    arry.push({
                      country: '发送方向带宽利用率',
                      year: resultBody[i].time.substr(0, 19),
                      value: resultBody[i].data.values[key]
                    });
                  }
                }
                _this.portChart.changeData(arry);
                _this.loading = false;
              }
            }
          }
        }
      });
      _this.portChart.render();
    },
    // 自定义监控
    otherInit () {
      let _this = this;
      _this.clearPortChart();
      // 创建图表
      _this.portChart = new Chart({
        container: 'charts',
        autoFit: true,
        height: 400
      });
      _this.loading = true;
      // X轴显示格式
      _this.portChart.scale('year', {
        type: 'time',
        mask: 'YYYY-MM-DD HH:mm:ss'
      });
      // Y轴参数设置
      _this.portChart.scale('value', {
        nice: true,
        min: 0
      });
      // 图表提示框设置
      _this.portChart.tooltip({
        showCrosshairs: true,
        shared: true,
        customItems: (items) => {
          items.map(ind => {
            if (ind.name === '端口发送流量速率' || ind.name === '端口接收流量速率') {
              ind.value = _this.$options.filters['filterBPS'](ind.value);
            } else {
              ind.value = ind.value + '%';
            }
          });
          return items;
        },
      });
      // 显示文字色值
      _this.portChart.line().position('year*value').color('country', ['#D47625', '#60A38B', '#6495fa', '#5ad8a6']);
      _this.dayTimes = _this.dayTimes ? _this.dayTimes : [];
      if (_this.dayTimes.length === 0) {
        _this.$message.info('自定义最大监控范围：30天前0点 - 昨天24点');
        let charts = document.getElementById('charts');
        if (charts) {
          document.getElementById('charts').innerHTML = '';
        }
        _this.loading = false;
      } else {
        _this.$http.post({
          url: '/api/sdwan/pm/appoint',
          data: {
            neId: Number(_this.neId),
            poId: '003',
            name: _this.name,
            startTime: _this.dayTimes[0],
            endTime: _this.dayTimes[1]
          }
        }).then(res => {
          let { status, resultBody } = res;
          if (resultBody.length === 0) {
            _this.$message.warning('暂无数据！');
            _this.portChart.changeData([]);
            _this.loading = false;
          } else {
            resultBody.splice(0, 1);
            if (status === '0') {
              let arry = [];
              for (let i = 0; i < resultBody.length; i++) {
                let onName = _this.name.toUpperCase();
                let portName = [onName.substring(0, onName.indexOf('-')), onName.substring(onName.indexOf('-') + 1, onName.indexOf('/')), onName.substring(onName.indexOf('/') + 1, onName.length)];
                let arr = resultBody[i].data.name.split(',');
                let list = arr[1].split('=');
                let ports = [list[0], arr[0].substring(arr[0].lastIndexOf('/') + 1, arr[0].length), list[1]];
                if (_this.vlan) {
                  portName.push(_this.vlan);
                  if (resultBody[i].data.name.indexOf('子接口') > -1) {
                    ports.push(arr[2].substring(arr[2].indexOf('=') + 1, arr[2].length));
                  }
                }
                let parStr = portName.join(',');
                let sonStr = ports.join(',');
                if (parStr === sonStr) {
                  // eslint-disable-next-line guard-for-in
                  for (let key in resultBody[i].data.values) {
                    // eslint-disable-next-line max-depth
                    if (key === '003_003') {
                      arry.push({
                        country: '端口发送流量速率',
                        year: resultBody[i].time.substr(0, 19),
                        value: resultBody[i].data.values[key]
                      });
                    }
                    // eslint-disable-next-line max-depth
                    if (key === '003_002') {
                      arry.push({
                        country: '端口接收流量速率',
                        year: resultBody[i].time.substr(0, 19),
                        value: resultBody[i].data.values[key]
                      });
                    }
                    // eslint-disable-next-line max-depth
                    if (key === '003_004') {
                      arry.push({
                        country: '接收方向带宽利用率',
                        year: resultBody[i].time.substr(0, 19),
                        value: resultBody[i].data.values[key]
                      });
                    }
                    // eslint-disable-next-line max-depth
                    if (key === '003_005') {
                      arry.push({
                        country: '发送方向带宽利用率',
                        year: resultBody[i].time.substr(0, 19),
                        value: resultBody[i].data.values[key]
                      });
                    }
                  }
                  _this.portChart.changeData(arry);
                  _this.loading = false;
                }
              }
            }
          }
        });
        _this.portChart.render();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.device {
  width: 100%;
  background: #fff;
  position: relative;
  box-sizing: border-box;
  border-radius: 3px;
  .title {
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    color: #555;
    font-size: 15px;
    i {
      border-radius: 50%;
      padding: 3px;
      margin-left: 10px;
    }
  }
  .content {
    padding: 15px;
    ::v-deep .el-radio-group {
      margin-bottom: 15px;
    }
    ::v-deep .el-alert {
      margin-bottom: 15px;
    }
    ::v-deep .el-date-editor {
      float: right;
    }
  }
}

@media only screen and (max-width: $device-ipad) {
  .device {
    .content {
      ::v-deep .el-date-editor {
        width: 100%;
        float: left;
        margin-bottom: 15px;
      }
    }
  }
}
</style>